package com.itheima.service.db.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.domain.db.AnalysisByDay;
import com.itheima.domain.db.LastYear;
import com.itheima.domain.db.ThisYear;
import com.itheima.mapper.AnalysisByDayMapper;
import com.itheima.mapper.LogMapper;
import com.itheima.service.db.AnalysisByDayService;
import com.itheima.utils.ComputeUtil;
import com.itheima.vo.AnalysisSummaryVo;
import com.itheima.vo.DataStatisticsVo;
import org.apache.dubbo.config.annotation.Service;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author Guanxing
 * @date 2021/10/7
 */
@Service
public class AnalysisByDayServiceImpl implements AnalysisByDayService {

    @Autowired
    private AnalysisByDayMapper analysisByDayMapper;

    @Autowired
    private LogMapper logMapper;

    //记录今日日志数据
    @Override
    public void saveOrUpdate() {
        String yesterday = DateUtil.yesterday().toString("yyyy-MM-dd");
        String today = DateUtil.today();
        //查询是否有今日数据
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("record_date", today);
        AnalysisByDay analysisByDay = analysisByDayMapper.selectOne(queryWrapper);

        //查询今日新增用户数
        Integer numRegistered = logMapper.selectByType("0102", today);
        //查询今日活跃用户数
        Integer numActive = logMapper.selectNumActive(today);
        //查询今日登录次数
        Integer numLogin = logMapper.selectByType("0101", today);
        //查询次日留存
        Integer numRetention1d = logMapper.selectNumRetention1d(today, yesterday);

        if (analysisByDay == null) {
            //执行保存
            analysisByDay = new AnalysisByDay();
            analysisByDay.setRecordDate(new Date());
            analysisByDay.setNumRegistered(numRegistered);
            analysisByDay.setNumActive(numActive);
            analysisByDay.setNumLogin(numLogin);
            analysisByDay.setNumRetention1d(numRetention1d);
            analysisByDay.setCreated(new Date());
            //analysisByDayMapper.insert(analysisByDay);
        } else {
            //执行修改
            /*analysisByDay.setRecordDate(new Date());
            analysisByDay.setNumRegistered(numRegistered);
            analysisByDay.setNumActive(numActive);
            analysisByDay.setNumLogin(numLogin);
            analysisByDay.setNumRetention1d(numRetention1d);
            analysisByDay.setUpdated(new Date());
            analysisByDayMapper.updateById(analysisByDay);*/
        }

    }

    //概要统计
    @Override
    public AnalysisSummaryVo summary() {
        //创建返回vo
        AnalysisSummaryVo vo = new AnalysisSummaryVo();

        String today = DateUtil.today();
        String yesterday = DateUtil.offsetDay(new Date(), -1).toString("yyyy-MM-dd");
        //今日数据
        QueryWrapper queryWrapper1 = new QueryWrapper();
        queryWrapper1.eq("record_date", today);
        AnalysisByDay todayAnalysisByDay = analysisByDayMapper.selectOne(queryWrapper1);
        //昨日数据
        QueryWrapper queryWrapper2 = new QueryWrapper();
        queryWrapper2.eq("record_date", yesterday);
        AnalysisByDay yesterdayAnalysisByDay = analysisByDayMapper.selectOne(queryWrapper2);

        //统计累计用户数
        Long cumulativeUsers = analysisByDayMapper.sumCumulativeUsers();
        //统计过去30天活跃用户数
        String beginDate30 = DateUtil.offsetDay(new Date(), -30).toString("yyyy-MM-dd");
        Long activePassMonth = analysisByDayMapper.selectActiveByTime(beginDate30, today);
        //统计过去7天活跃用户数
        String beginDate7 = DateUtil.offsetDay(new Date(), -7).toString("yyyy-MM-dd");
        Long activePassWeek = analysisByDayMapper.selectActiveByTime(beginDate7, today);

        if (todayAnalysisByDay == null) {
            todayAnalysisByDay = new AnalysisByDay();
        }
        if (yesterdayAnalysisByDay == null) {
            yesterdayAnalysisByDay = new AnalysisByDay();
        }
        //赋值
        vo.setCumulativeUsers(cumulativeUsers);
        vo.setActivePassMonth(activePassMonth);
        vo.setActivePassWeek(activePassWeek);
        vo.setNewUsersToday(todayAnalysisByDay.getNumRegistered().longValue());
        //今日新增用户涨跌率
        BigDecimal newUsersTodayRate = ComputeUtil.computeRate(todayAnalysisByDay.getNumRegistered(), yesterdayAnalysisByDay.getNumRegistered());
        vo.setNewUsersTodayRate(newUsersTodayRate);
        //今日登录次数
        vo.setLoginTimesToday(todayAnalysisByDay.getNumLogin().longValue());
        //今日登录次数涨跌率
        BigDecimal loginTimesTodayRate = ComputeUtil.computeRate(todayAnalysisByDay.getNumLogin(), yesterdayAnalysisByDay.getNumLogin());
        vo.setLoginTimesTodayRate(loginTimesTodayRate);
        //今日活跃用户数量
        vo.setActiveUsersToday(todayAnalysisByDay.getNumActive().longValue());
        //今日活跃用户涨跌率
        BigDecimal activeUsersTodayRate = ComputeUtil.computeRate(todayAnalysisByDay.getNumActive(), yesterdayAnalysisByDay.getNumActive());
        vo.setActiveUsersTodayRate(activeUsersTodayRate);

        //返回数据
        return vo;
    }

    //新增、活跃用户、次日留存率
    @Override
    public DataStatisticsVo dashboard(Long sd, Long ed, String type) {
        //去年
        DateTime dateTime = DateUtil.offset(new Date(sd), DateField.YEAR, -1);
        //Long类型转换Integer 时间段(几天)
        Integer indexDay = Math.toIntExact((ed - sd) / 86400000);
        //创建
        DataStatisticsVo vo = new DataStatisticsVo();

        List<LastYear> lastYears = new ArrayList<>();
        List<ThisYear> thisYears = new ArrayList<>();
        //类型对比("101"新增用户)
        if (StrUtil.equals("101", type)) {
            for (int i = 0; i < indexDay; i++) {
                LastYear lastYear = new LastYear();
                ThisYear thisYear = new ThisYear();
                //去年
                String s = DateUtil.offsetDay(dateTime, +i).toString();
                //切割后缀(空格后面的) 取前值跟数据库时间保持一直
                String[] split = s.split("\\s");
                String date1 = split[0];
                //根据时间查找新增用户次数
                Integer cout1 = analysisByDayMapper.findNumRegistered(date1);
                lastYear.setAmount(cout1);//数量
                lastYear.setTitle(date1);//日期
                lastYears.add(lastYear);
                //封装
                vo.setLastYear(lastYears);
                //今年
                String s2 = DateUtil.offsetDay(new Date(sd), +i).toString();
                String[] split2 = s2.split("\\s");
                String date2 = split2[0];

                Integer cout2 = analysisByDayMapper.findNumRegistered(date2);
                thisYear.setAmount(cout2);
                thisYear.setTitle(date2);
                thisYears.add(thisYear);
                vo.setThisYear(thisYears);

            }
        }
        //类型对比("102"活跃用户)
        if (StrUtil.equals("102", type)) {
            for (int i = 0; i < indexDay; i++) {
                LastYear lastYear = new LastYear();
                ThisYear thisYear = new ThisYear();
                //去年
                String s = DateUtil.offsetDay(dateTime, +i).toString();
                //切割后缀(空格后面的) 取前值跟数据库时间保持一直
                String[] split = s.split("\\s");
                String date1 = split[0];
                //根据时间查找活跃用户次数
                Integer cout1 = analysisByDayMapper.findNumActive(date1);
                lastYear.setAmount(cout1);//数量
                lastYear.setTitle(date1);//日期
                lastYears.add(lastYear);
                vo.setLastYear(lastYears);
                //今年
                String s2 = DateUtil.offsetDay(new Date(sd), +i).toString();
                String[] split2 = s2.split("\\s");
                String date2 = split2[0];

                Integer cout2 = analysisByDayMapper.findNumActive(date2);
                thisYear.setAmount(cout2);
                thisYear.setTitle(date2);
                thisYears.add(thisYear);
                vo.setThisYear(thisYears);

            }
        }
        //类型对比("103"次日留存率)
        if (StrUtil.equals("103", type)) {
            for (int i = 0; i < indexDay; i++) {
                LastYear lastYear = new LastYear();
                ThisYear thisYear = new ThisYear();
                //去年
                String s = DateUtil.offsetDay(dateTime, +i).toString();
                String[] split = s.split("\\s");
                String date1 = split[0];

                Integer cout1 = analysisByDayMapper.findNumRetention1d(date1);
                lastYear.setAmount(cout1);
                lastYear.setTitle(date1);
                lastYears.add(lastYear);
                vo.setLastYear(lastYears);

                //今年
                String s2 = DateUtil.offsetDay(new Date(sd), +i).toString();
                String[] split2 = s2.split("\\s");
                String date2 = split2[0];

                Integer cout2 = analysisByDayMapper.findNumRetention1d(date2);
                thisYear.setAmount(cout2);
                thisYear.setTitle(date2);
                thisYears.add(thisYear);
                vo.setThisYear(thisYears);

            }
        }

        System.out.println(lastYears);
        System.out.println(thisYears);

        return vo;


    }


}
